﻿using System.Reflection;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using TinyEngine.Core.Common;
using TinyEngine.Core.GameClasses;
using TinyEngine.Core.Services;

namespace TinyEngine.Core
{
    public abstract class TinyGame : XnaGame
    {
        private TinyGameEngine engine;
        internal static TinyGame Instance;

        public static bool IsInEditor
        {
            get { return Instance == null; }
        }

        public TinyGame() 
        {
            Instance = this;
            ServiceManager.RegisterService(new AssemblyService());

#if(WINDOWS_PHONE)
            graphics.IsFullScreen = true;
#endif
        }

        public static TinyGameEngine InitGameEngine(GraphicsDevice gfx, Microsoft.Xna.Framework.Content.ContentManager content)
        {
            return new TinyGameEngine(gfx, content);
        }

        protected override void Initialize()
        {
            engine = InitGameEngine(GraphicsDevice, Content);         
            
            SetupServices();

            ServiceManager.RegisterService(new RenderTargetService());

            ServiceManager.GetService<AssetLibrary>().GetContentRoot = GetContentRoot;

            base.Initialize();
         
        }

        private string GetContentRoot()
        {
            return this.Content.RootDirectory;
        }

        private void SetupServices()
        {
            ServiceManager.RegisterService(engine);
            ServiceManager.RegisterService(new ContentManagerService(this.Content));
            
            SetupDefaultServices();
        }

        public static void SetupDefaultServices()
        {
            ServiceManager.RegisterService(new InputService());
            ServiceManager.RegisterService(new AssetLibrary());
            ServiceManager.RegisterService(new Renderer.SpriteBatchService());
            ServiceManager.RegisterService(new Renderer.PrimitiveBatchService());
            ServiceManager.RegisterService(new SceneManager());
        }

        protected override void LoadContent()
        {
            base.LoadContent();
            InitializationComplete();
        }

        protected override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);

            engine.Draw(gameTime);
        }

        protected override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            engine.Update(gameTime);

            Interpolator.Update((float)gameTime.ElapsedGameTime.TotalSeconds);
        }

        public abstract void InitializationComplete();

        protected void SetDebugFont(string location)
        {
            ServiceManager.GetService<AssetLibrary>().AddFont("DEBUGFONT", location, false);
        }

    }
}
